package main.filters;

import java.io.IOException;
import java.io.Serializable;

import javax.inject.Inject;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import main.security.UserSession;

@WebFilter(filterName = "SecurityFilter", urlPatterns = {"/restricted/*", "/services/*"})
public class SecurityFilter implements Filter, Serializable {

	/**
	 * GUID for Serializable.
	 */
	private static final long serialVersionUID = 4867006040097404784L;
	
	@Inject
	private UserSession userBean;

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		if(userBean.isSignedIn() || httpRequest.getRequestURI().equals("/PatientFirst/services/userservice/login")) {
			chain.doFilter(request, response);
			return;
		}
		
		System.out.println("Invalid Access Attempt.");
		httpResponse.sendRedirect("/PatientFirst/index.html");
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
